package com.gxuwz.stats.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.config.CurrentLoginUserUtil;
import com.gxuwz.stats.entity.TotalWork;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.TotalWorkService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userTotalWork")
public class TotalWorkUserController {
    @Autowired
    private TotalWorkService totalWorkService;
    @Autowired
    private UserService userService;

    @GetMapping("/totalWorkUserList")
    public ResponseEntity<Map<String, Object>> totalWorkList(
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 使用工具类获取当前用户ID
            String currentUserId = CurrentLoginUserUtil.getCurrentUserId();
//            System.out.println("工具类获取到 的当前用户Id="+currentUserId);
            if (currentUserId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<TotalWork> page = new Page<>(currentPage, pageSize);
            QueryWrapper<TotalWork> queryWrapper = new QueryWrapper<>();

            // 添加当前登录用户的过滤条件
            queryWrapper.eq("user_id", currentUserId); // 根据 user_id 进行过滤


            // 调用 service 层的分页查询方法
            IPage<TotalWork> resultPage = totalWorkService.getUserTotalWorkListWithInfo(page, queryWrapper);
//            System.out.println("用户总工作量的查询结果="+resultPage);

//            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            System.out.println("总记录数="+resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @GetMapping("/export")
    public void exportTotalWork(
            @RequestParam(value = "year", required = false) String year,
            @RequestHeader("Authorization") String authorization,
            HttpServletResponse response) throws Exception {
        // 1. 解析token获取userId
        String token = authorization.replace("Bearer ", "");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String userId = jwtTokenUtil.getUserIdFromToken(token);

        // 2. 查找用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("user_id", userId));
        String username = user != null ? user.getUsername() : "未知用户";

        // 3. 查询 TotalWork（可按年份筛选）
        QueryWrapper<TotalWork> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId); // 只查当前用户
        if (year != null && !year.isEmpty()) {
            queryWrapper.like("total_work_year", year.substring(0, 4));
        }
        List<TotalWork> list = totalWorkService.list(queryWrapper);

        // 4. 补全用户信息到每条 TotalWork
        for (int i = 0; i < list.size(); i++) {
            TotalWork tw = list.get(i);
            tw.setRowNum(i + 1); // 序号
            if (user != null) {
                tw.setUsername(user.getUsername());
                tw.setDepartment(user.getDepartment());
                tw.setDegree(user.getDegree());
                tw.setPosition(user.getPosition());
                tw.setPost(user.getPost());
                tw.setQuotaStandard(user.getQuotaStandard());
            }
        }

        // 5. 生成文件名
        String now = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new java.util.Date());
        String fileName = "总工作量-" + username + "-" + now + ".xlsx";

        // 6. 导出
        ExcelExportUtil.export(response, list, TotalWork.class, "总工作量", fileName);
    }

//    /**
//     * 增加
//     * @param totalWork
//     * @return
//     */
//    @PostMapping("/addUserTotalWork")
//    public ResponseEntity<Map<String, Object>> saveUserTotalWork(@RequestBody TotalWork totalWork) {
//        System.out.println("前端数据：" + totalWork);
//
//        // 创建响应 Map
//        Map<String, Object> response = new HashMap<>();
//        //1. 验证 username 是否存在
//        String username = totalWork.getUsername();
//        if (username == null || username.isEmpty()) {
//            response.put("code", 400);
//            response.put("msg", "用户名不能为空");
//            return ResponseEntity.badRequest().body(response);
//        }
//
//        // 2. 根据 username 查询 user_id
//        Integer userId = userService.getUserIdByUsername(username);
//        if (userId == null) {
//            response.put("code", 400);
//            response.put("msg", "用户不存在");
//            return ResponseEntity.badRequest().body(response);
//        }
//        System.out.println("获取到的 user_id：" + userId);
//
//        // 3. 设置 user_id 并保存
//        totalWork.setUserId(userId);
//        try {
//            // 保存到数据库
//            totalWorkService.save(totalWork);
//
//            // 返回成功响应
//            response.put("code", 200);
//            response.put("msg", "新增成功");
//            return ResponseEntity.status(HttpStatus.CREATED).body(response);
//        } catch (Exception e) {
//            response.put("code", 500);
//            response.put("msg", "服务器内部错误");
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
//        }
//    }
//
//    /**
//     * 修改
//     */
//    @PutMapping("/updateUserTotalWork")
//    public ResponseEntity<Map<String, Object>> updateUserTotalWork(
//            @RequestBody TotalWork totalWork
////            @RequestHeader("Authorization") String authorization
//    ) {
//        totalWorkService.updateById(totalWork);
//        Map<String, Object> response = new HashMap<>();
//        response.put("code", 200);
//        response.put("msg", "修改成功");
//        return ResponseEntity.ok(response);
//    }
}
